﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using System.IO;

namespace T3K.SketchEditor.Configuration {

    [Serializable]
    public abstract class SettingsBase {

        public const string Ext = "xml";
        public const string BaseBath = "Config";

        private string _configName;
        private FileInfo _file;

        public string ConfigName {
            get { return _configName; }
            set { 
                _configName = value;
                Init();
            }
        }

        protected SettingsBase() { }

        public SettingsBase(string configName) {
            _configName = configName;
            Init();
        }

        private void Init() {
            if (!Directory.Exists(BaseBath))
                Directory.CreateDirectory(BaseBath);
            _file = new FileInfo(Path.Combine(BaseBath, string.Format("{0}.{1}", _configName, Ext)));
        }

        protected static string ConfigFilePath(string configName) {
            if (!Directory.Exists(BaseBath))
                Directory.CreateDirectory(BaseBath);
            FileInfo file = new FileInfo(Path.Combine(BaseBath, string.Format("{0}.{1}", configName, Ext)));
            return file.FullName;
        }

        public void Save() {
            SettingsBase.Save(_file.FullName, this);
        }

        public static void Save(string filename, SettingsBase obj) {
            FileStream fs = File.Open(filename, FileMode.Create);
            XmlSerializer s = new XmlSerializer(obj.GetType());
            s.Serialize(fs, obj);
            fs.Flush();
            fs.Close();
        }

        public static SettingsBase Open(string fileName, Type type) {
            FileStream fs = File.Open(fileName, FileMode.Open);
            XmlSerializer s = new XmlSerializer(type);
            object obj = s.Deserialize(fs);
            return obj as SettingsBase;
        }

    }
}
